# coding:utf-8
import threading

import redis


class RedisUtil(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __init__(self, batch_no):
        if not self._biz_inited:
            self._biz_inited = True
            self.rds = redis.StrictRedis(host='192.168.1.200', port='6379', db=3, decode_responses=True)
            self.task_set_key = 'ctaxccgp:order:task:{}'.format(batch_no)
            self.done_task_key = 'ctaxccgp:order:task:done:{}'.format(batch_no)

    def __new__(cls, *args, **kwargs):
        if not hasattr(RedisUtil, "_instance"):
            with RedisUtil._instance_lock:
                if not hasattr(RedisUtil, "_instance"):
                    RedisUtil._instance = object.__new__(cls)
        return RedisUtil._instance

    def exists_batch(self):
        return self.rds.exists(self.task_set_key)

    def init_tasks(self, vals):
        return self.rds.lpush(self.task_set_key, *vals)

    def add_task(self, val):
        return self.rds.lpush(self.task_set_key, val)

    def get_task(self):
        return self.rds.rpop(self.task_set_key)

    def is_task_done(self, sku_id):
        return self.rds.sismember(self.done_task_key, sku_id)

    def add_done_task(self, sku_id):
        return self.rds.sadd(self.done_task_key, sku_id)
